#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 13/4/2023 下午9:21
# Author: name
# File: environment.py
# ide: PyCharm
# description: 环境管理
import time

import jmespath
import requests
from pywebio.pin import put_textarea, put_select

from pywebio.output import *
from pywebio.pin import put_input, pin
from pywebio.session import eval_js

from backend.app.config import HOST
from commons.comms import close_pop, generate_uuid, is_not_empty, validate_url
from commons.json_tools import read_json_file, write_json_file
from frontend.menus import show_menus


def business_crud_data(action=None, item_id=None):
    if action == "save":
        environment_name = is_not_empty(pin.environment_name, "环境名称")
        environment_address = validate_url(pin.environment_address, "环境地址")
        environment_username = is_not_empty(pin.environment_username, "用户名")
        environment_password = is_not_empty(pin.environment_password, "密码")
        login_temp_id = is_not_empty(pin.login_temp_id, "登录模板")
        environment_desc = pin.environment_desc
        if environment_name and environment_address and environment_username and environment_password and login_temp_id:
            data = {
                "name": environment_name,
                "address": environment_address,
                "username": environment_username,
                "password": environment_password,
                "login_temp_id": login_temp_id,
                "description": environment_desc,
            }
            result = requests.post(HOST + "/environment/add", json=data)
            toast(result.json().get("message"))
    elif action == "update":
        environment_name = is_not_empty(pin.environment_name, "环境名称")
        environment_address = validate_url(pin.environment_address, "环境地址")
        environment_username = is_not_empty(pin.environment_username, "用户名")
        environment_password = is_not_empty(pin.environment_password, "密码")
        login_temp_id = is_not_empty(pin.login_temp_id, "登录模板")
        print("更新", login_temp_id)
        environment_desc = pin.environment_desc
        if environment_name and environment_address and environment_username and environment_password and login_temp_id:
            data = {
                "name": environment_name,
                "address": environment_address,
                "username": environment_username,
                "password": environment_password,
                "login_temp_id": login_temp_id,
                "description": environment_desc,
            }
            result = requests.put(HOST + f"/environment/{item_id}", json=data)
            toast(result.json().get("message"))
    elif action == "delete":
        result = requests.delete(HOST + f"/environment/{item_id}")
        toast(result.json()["message"])
        time.sleep(1)
        eval_js("window.location.reload();")
    else:
        pass


def html_update_environment(data, login_temp_id):
    result = requests.get(HOST + "/login/list")
    print(result.text)
    id_list = jmespath.search("@[].id", result.json())
    name_list = jmespath.search("@[].name", result.json())
    login_temp_name = jmespath.search(f"@[?@.id==`{login_temp_id}`].name|[0]", result.json())
    print(login_temp_name)
    login_temp_list = []
    for x, y in zip(name_list, id_list):
        login_temp_list.append((x, y))

    return popup('环境编辑', [
        put_row([
            put_text("环境名称"),
            put_text("*").style("color:red"),
            put_input("environment_name", value=data[1]),
        ], size="15% 5% 70%"),
        put_row([
            put_text("环境地址"),
            put_text("*").style("color:red"),
            put_input("environment_address", value=data[2]),
        ], size="15% 5% 70%"),
        put_row([
            put_text("用户名"),
            put_text("*").style("color:red"),
            put_input("environment_username", value=data[3]),
        ], size="15% 5% 70%"),
        put_row([
            put_text("密码"),
            put_text("*").style("color:red"),
            put_input("environment_password", value=data[4]),
        ], size="15% 5% 70%"),
        put_row([
            put_text("登录模板"),
            put_text("*").style("color:red"),
            put_select("login_temp_id", options=login_temp_list, value=(login_temp_name, login_temp_id)),
        ], size="15% 5% 70%"),
        put_row([
            put_text("描述信息"),
            put_textarea("environment_desc", rows=5, value=data[5])
        ], size="20% 70%"),
        put_row([
            None,
            put_button("提交", onclick=lambda: business_crud_data("update", data[0]), small=True),
            put_button('关闭', onclick=lambda: close_pop(), color="secondary", small=True)
        ], size="70% 15%"),

    ], size="large", closable=False)


def html_add_environment():
    result = requests.get(HOST + "/login/list")
    print(result.text)
    id_list = jmespath.search("@[].id", result.json())
    name_list = jmespath.search("@[].name", result.json())
    login_temp_list = []
    for x, y in zip(name_list, id_list):
        login_temp_list.append((x, y))
    return popup('环境新增', [
        put_row([
            put_text("环境名称"),
            put_text("*").style("color:red"),
            put_input("environment_name"),
        ], size="15% 5% 70%"),
        put_row([
            put_text("环境地址"),
            put_text("*").style("color:red"),
            put_input("environment_address"),
        ], size="15% 5% 70%"),
        put_row([
            put_text("用户名"),
            put_text("*").style("color:red"),
            put_input("environment_username"),
        ], size="15% 5% 70%"),
        put_row([
            put_text("密码"),
            put_text("*").style("color:red"),
            put_input("environment_password"),
        ], size="15% 5% 70%"),
        put_row([
            put_text("登录模板"),
            put_text("*").style("color:red"),
            put_select("login_temp_id", login_temp_list),
        ], size="15% 5% 70%"),
        put_row([
            put_text("描述信息"),
            put_textarea("environment_desc", rows=5)
        ], size="20% 70%"),
        put_row([
            None,
            put_button("提交", onclick=lambda: business_crud_data("save"), small=True),
            put_button('关闭', onclick=lambda: close_pop(), color="secondary", small=True)
        ], size="70% 15%"),

    ], size="large", closable=False)


def get_page_data(page: int = 1, size: int = 5, name: str = None):
    query_param = {
        "page": page,
        "size": size,
        "name": name if name else ""
    }
    response = requests.get(HOST + "/environment/page", params=query_param)

    print(response.text)
    variable_json = response.json().get("results")
    total = response.json().get("total")
    search_key = response.json().get("search_key")
    data_list = []
    if variable_json:
        data_list = jmespath.search("[].values(@)", variable_json)
    for v in data_list:
        login_temp_id = v.pop()
        print("---------------", login_temp_id)
        exec_code = f"""
v.append(
    put_row([
        put_button("编辑", onclick=lambda: html_update_environment({v},{login_temp_id}),small=True),
        None,
        put_button("删除", onclick=lambda: business_crud_data("delete",{v[0]}),color="danger",small=True),
    ]
    )
)
"""
        exec(exec_code)
    print(data_list)
    return total, page, search_key, data_list


def business_pages_data(current_page=1, page_size=10, name=None):
    page_size = 10
    print(f"当前第{current_page}页")
    if current_page < 1:
        current_page = 1
        toast("当前第一页")
        return
    total, current_page, search_key, data_list = get_page_data(current_page, page_size, name)
    if total <= page_size:
        total_page = 1
    else:
        total_page = int(total / page_size) + 1
    if current_page > total_page:
        current_page = total_page
        toast("当前最后一页")
        return
    table_header = [
        put_html('<h4 style="width:40px">编号</h4>'),
        put_html('<h4 style="width:150px">环境名称</h4>'),
        put_html('<h4 style="width:200px">环境地址</h4>'),
        put_html('<h4 style="width:100px">用户名</h4>'),
        put_html('<h4 style="width:100px">密码</h4>'),
        put_html('<h4 style="width:100px">描述信息</h4>'),
        put_html('<h4 style="width:150px">创建时间</h4>'),
        put_html('<h4 style="width:150px">更新时间</h4>'),
        put_html('<h4 style="width:100px">操作</h4>'),
    ]
    with use_scope("data_list", clear=True):
        put_tabs(
            [
                {
                    "title": "环境列表",
                    "content": [
                        put_button("新增", onclick=lambda: html_add_environment(), small=True),
                        put_row(
                            [
                                put_text("环境名称: "),
                                put_input(name="env_search", placeholder="请输入环境名称进行查询", value=search_key),
                                None,
                                put_button("搜索",
                                           onclick=lambda: business_pages_data(name=pin.env_search), small=True),
                                put_button("重置",
                                           onclick=lambda: business_pages_data(), small=True),
                            ], size="8% 50% 5% 6%"
                        ),
                        put_table(data_list, header=table_header),
                        put_row([
                            put_text(
                                f"      每页{page_size}条      当前第{current_page}/{total_page}页       总共{total}条"),
                            put_button("上一页",
                                       onclick=lambda: business_pages_data(current_page - 1, page_size), small=True),

                            put_button("下一页",
                                       onclick=lambda: business_pages_data(current_page + 1, page_size), small=True),

                        ], size="40% 6% 6%"
                        )

                    ]
                }
            ], scope="data_list"
        )


def html_show_environment():
    """
    环境管理
    """
    show_menus()
    business_pages_data()
